<script>
import empty from "../../../components/empty.vue"
import request from "../../../utils/request"
import { cloneDeep, handleMoney } from "@/utils"
import behavior from "./behavior"

const pagination = {
  current: 1,
  size: 10,
}
export default {
  name: "index",
  components: { empty },
  data() {
    return {
      isEmpty: false,
      tabList: [
        { label: "全部", value: "" },
        { label: "待付款", value: "WaitPay" },
        { label: "已完成", value: "Success" },
      ],
      currentActiveTab: "",
      orderList: [],
      pagination: cloneDeep(pagination),
      total: 0,
      loadMoreStatusText: "more",
      behavior,
      lastOpenDetailOrderId: "", //上次打开详情的订单id
    }
  },
  async onShow() {
    if (!this.lastOpenDetailOrderId) {
      await this.reLoadData()
    } else {
      this.getOrderDetail()
    }
  },
  methods: {
    handleMoney,
    //重置分页重新获取数据
    async reLoadData() {
      try {
        uni.showLoading({
          title: "加载中",
          mask: true,
        })
        this.orderList = []
        this.pagination = cloneDeep(pagination)
        this.total = 0
        await this.getOrderList()
      } finally {
        uni.hideLoading()
      }
    },
    //获取订单列表
    getOrderList() {
      return new Promise((resolve, reject) => {
        this.loadMoreStatusText = "loading"
        request({
          url: "ord/getOrdList",
          data: {
            ordStatusCode: this.currentActiveTab,
            ...this.pagination,
          },
          errorHandle: true,
        })
          .then((res) => {
            this.isEmpty = res.total === 0
            this.total = res.total
            this.orderList.push(...res.records)
            if (this.orderList.length >= this.total) {
              this.loadMoreStatusText = "noMore"
            } else {
              this.loadMoreStatusText = "more"
            }
            resolve()
          })
          .catch((_) => {
            reject()
          })
      })
    },
    //查看订单详情
    viewOrderDetail(item) {
      this.lastOpenDetailOrderId = item.ordNo
      uni.navigateTo({
        url: "/pages/mine/orderList/detail?ordNo=" + item.ordNo,
      })
    },
    //获取订单详情(用于从订单详情页回来的时候刷新列表中的某一条订单的数据）
    getOrderDetail() {
      request({
        url: "ord/getOrdDetailInfo",
        data: {
          ordNo: this.lastOpenDetailOrderId,
        },
        errorHandle: true,
        showLoading: true,
      }).then((data) => {
        const index = this.orderList.findIndex((item) => item.ordNo === this.lastOpenDetailOrderId)
        if (index !== -1) {
          for (let orderListElementKey in this.orderList[index]) {
            this.orderList[index][orderListElementKey] = data[orderListElementKey]
          }
        }
      })
    },
  },
  //下拉刷新
  async onPullDownRefresh() {
    await this.reLoadData()
    uni.stopPullDownRefresh()
  },
  //下滑到底触发，加载下一页
  async onReachBottom() {
    if (this.loadMoreStatusText === "noMore") return
    this.pagination.current++
    await this.getOrderList()
  },
}
</script>

<template>
  <view class="page">
    <view class="header">
      <view
        class="tab-item"
        v-for="item in tabList"
        :key="item.value"
        :class="{ active: currentActiveTab === item.value }"
        @click="
          () => {
            currentActiveTab = item.value
            reLoadData()
          }
        "
      >
        <view class="label">
          {{ item.label }}
          <view class="active-bar" v-if="currentActiveTab === item.value"></view>
        </view>
      </view>
    </view>
    <view class="placeholder"></view>
    <view class="content" v-if="!isEmpty">
      <view class="order-list-item" v-for="item in orderList" :key="item.ordNo">
        <view @click.stop="viewOrderDetail(item)" class="order-item">
          <view class="header">
            <!--				订单编号-->
            <view class="order-no">订单编号：{{ item.ordNo }}</view>
            <!--					订单状态-->
            <view class="order-status">
              <text :class="[behavior.getClassByStatus(item.ordStatusCode)]">{{ item.ordStatusName }} </text>
            </view>
          </view>
          <!--				订单分类-->
          <view class="order-class">{{ item.ordClassName }}</view>
          <!--				商品数量和订单总价-->
          <view class="product-price">
            <view class="text">合计：</view>
            <view class="unit primary">￥</view>
            <view class="number primary">{{ handleMoney(item.ordSum) }}</view>
          </view>
          <!--				分割线-->
          <view class="divide-line"></view>
        </view>
        <!--				底部按钮-->
        <view class="footer-btn">
          <!--					取消支付按钮（订单状态为待支付时展示）-->
          <view
            class="button plain"
            v-if="['WaitPay'].includes(item.ordStatusCode)"
            @click.stop="
              behavior.cancelOrder(item).then(() => {
                lastOpenDetailOrderId = item.ordNo
                getOrderDetail()
              })
            "
            >取消订单
          </view>
          <!--					立即支付按钮（只在订单状态为待支付时展示）-->
          <view class="button primary" v-if="item.ordStatusCode === 'WaitPay'" @click.stop="behavior.orderPay(item).then(reLoadData)"
            >立即支付
          </view>
          <!--					订单详情按钮（订单状态不为待支付时展示）-->
          <view class="button plain" v-if="!['WaitPay'].includes(item.ordStatusCode)" @click.stop="viewOrderDetail(item)">订单详情 </view>
        </view>
      </view>
      <!--			下拉到底加载下一页-->
      <uni-load-more style="margin-top: 30rpx" :status="loadMoreStatusText"></uni-load-more>
    </view>
    <empty v-else height="calc(100vh - 100rpx)"></empty>
  </view>
</template>

<style scoped lang="scss">
.page {
  width: 100vw;
  min-height: 100vh;
  background-color: #f5f5f5;

  > .header {
    background-color: #fff;
    box-shadow: 0 4rpx rgba(0, 0, 0, 0.1);
    display: flex;
    overflow: auto;
    width: 100vw;
    position: fixed;
    left: 0;
    top: 0;

    > .tab-item {
      min-width: 33%;
      display: flex;
      padding: 30rpx 0;
      justify-content: center;
      align-items: center;
      flex-direction: column;

      &.active {
        > .label {
          color: var(--text-color-theme);
          font-weight: 500;
          position: relative;

          > .active-bar {
            position: absolute;
            bottom: -12rpx;
            width: 50%;
            height: 6rpx;
            background-color: var(--text-color-theme);
            left: 50%;
            transform: translateX(-50%);
          }
        }
      }

      > .label {
        color: var(--text-color);
        font-size: 30rpx;
      }
    }
  }

  > .placeholder {
    height: 100rpx;
  }

  > .content {
    padding-bottom: calc(30rpx + env(safe-area-inset-bottom));

    > .order-list-item {
      margin-top: 30rpx;
      background: white;
      padding: 30rpx;

      .order-item {
        > .header {
          display: flex;
          align-items: center;
          justify-content: space-between;

          > .order-no {
            font-size: 28rpx;
            color: var(--text-color);
          }

          > .order-status {
            font-size: 32rpx;

            > .success {
              color: #149764;
            }

            > .info {
              color: var(--text-color-light);
            }

            > .warning {
              color: #d0a30e;
            }
          }
        }

        > .order-class {
          font-size: 34rpx;
          color: var(--text-color);
          margin-top: 30rpx;
        }

        > .product-price {
          display: flex;
          align-items: flex-end;
          margin-top: 30rpx;
          justify-content: flex-end;

          > .text {
            font-size: 28rpx;
            color: var(--text-color-light);
          }

          > .primary {
            color: var(--text-color-theme);
          }

          > .unit {
            font-size: 28rpx;
          }

          > .number {
            font-size: 40rpx;
            line-height: 42rpx;
          }
        }

        > .divide-line {
          margin-top: 30rpx;
          height: 2rpx;
          background: var(--border-color);
        }
      }

      > .footer-btn {
        margin-top: 30rpx;
        display: flex;
        justify-content: flex-end;
        align-items: center;

        > .button {
          display: flex;
          align-items: center;
          justify-content: center;
        }

        > .button:not(:last-child) {
          font-size: 32rpx;
          margin-right: 30rpx;
        }

        > .primary {
          background-color: #f19d3d;
          color: white;
          padding: 0 54rpx;
          height: 64rpx;
          border-radius: 32rpx;
          font-weight: 500;
        }

        > .info {
          color: var(--text-color-light);
        }

        > .plain {
          color: var(--text-color-light);
          padding: 0 54rpx;
          height: 64rpx;
          border-radius: 32rpx;
          font-weight: 500;
          border: 4rpx solid var(--border-color);
        }
      }
    }
  }
}
</style>
